package com.ciaj.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciaj.base.comm.constant.DefaultConstant;
import com.ciaj.base.comm.utils.CollectionUtil;
import com.ciaj.base.comm.utils.CommUtil;
import com.ciaj.base.exception.BsRException;
import com.ciaj.module.sys.entity.po.SysUser;
import com.ciaj.module.sys.entity.vo.ShiroUser;
import com.ciaj.module.sys.entity.vo.SysJobVo;
import com.ciaj.module.sys.mapper.SysUserMapper;
import com.ciaj.module.sys.service.ISysJobService;
import com.ciaj.module.sys.service.ISysUserService;
import com.ciaj.base.bean.BaseServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* <p>
* 系统用户表 Gen 服务实现类
* </p>
*
* @author ciaj.
* @since 2020-08-14
*/
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private ISysJobService iSysJobService;


    @Override
    public ShiroUser getShiroUserById(String id) {
        SysUser sysUser = getById(id);
        return buildShiroUser(sysUser);
    }

    @Override
    public ShiroUser getShiroUserByAccount(String account) {
        SysUser sysUser = getSysUserByAccount(account);
        if (sysUser == null) {
            throw new BsRException(String.format("未获取到用户[%s]", account));
        }

        return buildShiroUser(sysUser);
    }

    @Override
    public SysUser getSysUserByAccount(String account) {
        SysUser sysUser = getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getAccount, account));
        return sysUser;
    }

    @Override
    public ShiroUser shiroUserJobChange(String jobId) {
        ShiroUser loginUser = (ShiroUser) CommUtil.getLoginUser();
        List<SysJobVo> jobVos = loginUser.getJobVos();
        SysJobVo sysJobVo = CollectionUtil.of(jobVos).filter(f -> f.getJobId().equals(jobId)).findFirst().orElse(loginUser.getJobVo());
        loginUser.setJobVo(sysJobVo);

        SecurityUtils.getSubject().getSession().setAttribute(DefaultConstant.LOGIN_USER, loginUser);
        return loginUser;
    }

    private ShiroUser buildShiroUser(SysUser sysUser) {
        ShiroUser shiroUser = new ShiroUser();
        BeanUtils.copyProperties(sysUser, shiroUser);
        SysJobVo job = new SysJobVo();
        shiroUser.setJobVo(job);
        List<SysJobVo> jobVos = iSysJobService.getJobVosByUserId(sysUser.getId());
        shiroUser.setJobVos(jobVos);
        if(CollectionUtil.isNotEmpty(jobVos)){
            SysJobVo sysJobVo = CollectionUtil.of(jobVos).filter(f -> DefaultConstant.FLAG_1.equals(f.getIsDefault())).findFirst().orElse(jobVos.get(0));
            shiroUser.setJobVo(sysJobVo);
        }
        return shiroUser;
    }
}
